package gr.handmademarket.ui.forms;

import gr.handmademarket.bl.operations.RegisterBuyerOperation;
import gr.handmademarket.po.implementations.Buyer;
import gr.handmademarket.ui.WebHandMadeSession;
import gr.handmademarket.ui.pages.RegisterPage;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

public class RegisterForm 
extends Form<Buyer>{

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1L;

	private TextField<String> usernameField = new RequiredTextField<String>("username");
	
	private TextField<String> passwordField = new PasswordTextField("password");
	
	private TextField<String> firstNameField = new RequiredTextField<String>("firstName");
	
	private TextField<String> lastNameField = new RequiredTextField<String>("lastName");
	
	private Buyer buyer;
	
	private Button signUpBtn = new Button("registerBtn"){
		/**
		 * serialVersionUID
		 */
		private static final long serialVersionUID = 1L;

		public void onSubmit() {
			RegisterBuyerOperation op = new RegisterBuyerOperation();
			op.setBuyer(buyer);
			String message;
			try{
				op.execute();
				WebHandMadeSession session = (WebHandMadeSession) WebHandMadeSession.get();
				session.setUser(op.getBuyer());
				message = "Registration process was completed successfully. You will receive an email for the activation of your account";
			} catch (Exception e){
				message = "Registration process was not completed successfully. Please try again"; 
			}
			PageParameters params = new PageParameters();
			params.add("message", message);
			setResponsePage(RegisterPage.class,params);
		};
	};
	
	public RegisterForm(String id, IModel<Buyer> model) {
		super(id, model);
		add(usernameField,passwordField,firstNameField,lastNameField,signUpBtn);
		buyer = model.getObject();
	}

}
